
package com.hlkj.pay.app.merchant.ext.impl.helipay;
/*
 * Hlpay-Plus aggregate payment system.
 * Copyright (c) 2024-2025 Hlpay Team Copyright has the right of final interpretation.
 */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.extension.annotation.Extension;
import com.hlkj.pay.app.merchant.ext.ChannelMerchantTransferExtPt;
import com.hlkj.pay.app.merchant.ext.MerchantExtConstant;
import com.hlkj.pay.app.merchant.ext.dto.payment.ChannelTransferContext;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.HeliPayEatrxConfig;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.eatrx.HeePayEatrxTransferQueryRes;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.eatrx.HeePayEatrxTransferSubmitRes;
import com.hlkj.pay.app.merchant.ext.impl.helipay.dto.eatrx.HeliPayEatrxAppChannelParams;
import com.hlkj.pay.app.merchant.ext.impl.helipay.handler.HeliPayMerchantEatrxCommonParamsHandle;
import com.hlkj.pay.dto.order.NotifyOrderTransferDto;
import com.hlkj.pay.enums.CommonEnum;
import com.hlkj.pay.enums.MerchantEnum;
import com.hlkj.pay.infrastructure.model.order.OrderTransferDO;
import com.hlkj.pay.infrastructure.model.pay.ProviderChannelConfigDO;
import com.hlkj.pay.util.DateUtils;
import com.hlkj.pay.util.MerchantUtils;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author HlpayTeam
 * @date 2024/11/20 17:19
 */
@Slf4j
@Repository
@RequiredArgsConstructor
@Extension(bizId = MerchantExtConstant.CHANNEL_HELIPAY_VIR)
public class HeliPayMerchantTransferExtPt extends HeliPayMerchantEatrxCommonParamsHandle implements ChannelMerchantTransferExtPt {

    @Override
    public void submitChannelSingleTransferApply(ChannelTransferContext channelTransferContext) {
        log.info("合利宝提交单笔转账申请 payOrderCode:{}", channelTransferContext.getOrderTransfer().getPayOrderNo());
        CommonResult<HeliPayEatrxConfig> configCommonResult = heliPayEatrxConfig(channelTransferContext.getProviderChannelConfig(), channelTransferContext.isTest());
        if (!configCommonResult.isSuccess()) {
            channelTransferContext.setRemark(configCommonResult.getMsg());
            channelTransferContext.setProcessStatus(false);
            return;
        }
        HeliPayEatrxConfig heliPayEatrxConfig = configCommonResult.getData();
        Map<String, Object> params = new HashMap<>();
        OrderTransferDO orderTransfer = channelTransferContext.getOrderTransfer();
        HeliPayEatrxAppChannelParams inMerchantReportDto = heePayAppChannelParams(channelTransferContext.getInMerchantAppChannelDO());
        HeliPayEatrxAppChannelParams outMerchantReportDto = heePayAppChannelParams(channelTransferContext.getMerchantAppChannelDO());
        params.put("outUserId", outMerchantReportDto.getUserId());
        params.put("outVirtualAccountNo", outMerchantReportDto.getVirtualAccountNo());
        params.put("inUserId", inMerchantReportDto.getUserId());
        params.put("inVirtualAccountNo", inMerchantReportDto.getVirtualAccountNo());
        params.put("orderNum", orderTransfer.getPayOrderNo());
        params.put("amount", MerchantUtils.bigDecimalToString2(orderTransfer.getAmount()));
        String url = url(channelTransferContext.isTest()) + "/ea/transferApply";
        try {
            // 再提交数据
            CommonResult<HeePayEatrxTransferSubmitRes> commonResult = transferRequest(params, url, HeePayEatrxTransferSubmitRes.class, heliPayEatrxConfig);
            if (!commonResult.isSuccess()) {
                channelTransferContext.setProcessStatus(false);
                channelTransferContext.setRemark(commonResult.getMsg());
                return;
            }
            HeePayEatrxTransferSubmitRes eatrxTransferSubmitRes = commonResult.getData();
            if (!eatrxTransferSubmitRes.success()) {
                channelTransferContext.setProcessStatus(false);
                channelTransferContext.setRemark(eatrxTransferSubmitRes.getRetMsg());
                return;
            }
            OrderTransferDO updateOrderTransfer = new OrderTransferDO();
            channelTransferContext.setUpdateOrderTransfer(updateOrderTransfer);
            updateOrderTransfer.setChannelOrderNo(eatrxTransferSubmitRes.getSerialNumber());
            updateOrderTransfer.setInUserId(inMerchantReportDto.getUserId());
            updateOrderTransfer.setOutUserId(outMerchantReportDto.getUserId());
            switch (eatrxTransferSubmitRes.getStatus()) {
                case "FAIL":
                    updateOrderTransfer.setStatus(MerchantEnum.PROCESS_STATUS.FAIL.getCode());
                    updateOrderTransfer.setMessage(eatrxTransferSubmitRes.getRetMsg());
                    break;
                case "SUCCESS":
                    updateOrderTransfer.setStatus(MerchantEnum.PROCESS_STATUS.INIT.getCode());
                    break;
            }
        }
        catch (Exception e) {
            channelTransferContext.setProcessStatus(false);
            channelTransferContext.setRemark(e.getMessage());
        }
    }

    @Override
    public void submitChannelSingleTransfer(ChannelTransferContext channelTransferContext) {
        log.info("合利宝提交单笔转账 payOrderCode:{}", channelTransferContext.getOrderTransfer().getPayOrderNo());
        CommonResult<HeliPayEatrxConfig> configCommonResult = heliPayEatrxConfig(channelTransferContext.getProviderChannelConfig(), channelTransferContext.isTest());
        if (!configCommonResult.isSuccess()) {
            channelTransferContext.setRemark(configCommonResult.getMsg());
            channelTransferContext.setProcessStatus(false);
            return;
        }
        HeliPayEatrxConfig heliPayEatrxConfig = configCommonResult.getData();
        Map<String, Object> params = new HashMap<>();
        OrderTransferDO orderTransfer = channelTransferContext.getOrderTransfer();
        HeliPayEatrxAppChannelParams inMerchantReportDto = heePayAppChannelParams(channelTransferContext.getInMerchantAppChannelDO());
        HeliPayEatrxAppChannelParams outMerchantReportDto = heePayAppChannelParams(channelTransferContext.getMerchantAppChannelDO());
        if(StringUtils.isEmpty(channelTransferContext.getOrderTransferVerifyDto().getSmsCode())){
            channelTransferContext.setProcessStatus(false);
            channelTransferContext.setRemark("短信验证码必填");
            return;
        }
        params.put("outUserId", outMerchantReportDto.getUserId());
        params.put("outVirtualAccountNo", outMerchantReportDto.getVirtualAccountNo());
        params.put("inUserId", inMerchantReportDto.getUserId());
        params.put("inVirtualAccountNo", inMerchantReportDto.getVirtualAccountNo());
        params.put("orderNum", orderTransfer.getPayOrderNo());
        params.put("amount", MerchantUtils.bigDecimalToString2(orderTransfer.getAmount()));
        params.put("remark", orderTransfer.getRemark());
        if (CommonEnum.YES_NO_TYPE.YES.getCode().equals(orderTransfer.getFeePayer())) {
            params.put("feeType", "RECEIVER");
        }
        else {
            params.put("feeType", "PAYER");
        }
        params.put("password", channelTransferContext.getPassword());
        Map<String, Object> extra = new HashMap<>();
        extra.put("orderNo", orderTransfer.getPayOrderNo());
        extra.put("orderAmount", MerchantUtils.bigDecimalToString2(orderTransfer.getAmount()));
        extra.put("productName", "虚拟户转账");
        extra.put("productCount", 1);
        params.put("extra", new HashMap<>().put("productInfos", new ArrayList<>() {

            {
                add(extra);
            }
        }));

        params.put("smsCode", channelTransferContext.getOrderTransferVerifyDto().getSmsCode());
        params.put("terminalType", "1");
        params.put("terminalIp", orderTransfer.getClientIp());
        params.put("terminalMac", "00:1A:2B:3C:4D:5E");

        String url = url(channelTransferContext.isTest()) + "/ea/transfer";
        try {
            // 再提交数据
            CommonResult<HeePayEatrxTransferSubmitRes> commonResult = transferRequest(params, url, HeePayEatrxTransferSubmitRes.class, heliPayEatrxConfig);
            if (!commonResult.isSuccess()) {
                channelTransferContext.setProcessStatus(false);
                channelTransferContext.setRemark(commonResult.getMsg());
                return;
            }
            HeePayEatrxTransferSubmitRes eatrxTransferSubmitRes = commonResult.getData();
            if (!eatrxTransferSubmitRes.success()) {
                channelTransferContext.setProcessStatus(false);
                channelTransferContext.setRemark(eatrxTransferSubmitRes.getRetMsg());
                return;
            }
            OrderTransferDO updateOrderTransfer = new OrderTransferDO();
            channelTransferContext.setUpdateOrderTransfer(updateOrderTransfer);
            updateOrderTransfer.setChannelOrderNo(eatrxTransferSubmitRes.getSerialNumber());
            updateOrderTransfer.setInUserId(inMerchantReportDto.getUserId());
            updateOrderTransfer.setOutUserId(outMerchantReportDto.getUserId());
            switch (eatrxTransferSubmitRes.getStatus()) {
                case "FAIL":
                    updateOrderTransfer.setStatus(MerchantEnum.PROCESS_STATUS.FAIL.getCode());
                    break;
                case "SUCCESS":
                    updateOrderTransfer.setStatus(MerchantEnum.PROCESS_STATUS.SUCCESS.getCode());
                    break;
                default:
                    updateOrderTransfer.setStatus(MerchantEnum.PROCESS_STATUS.DOING.getCode());
            }
        }
        catch (Exception e) {
            channelTransferContext.setProcessStatus(false);
            channelTransferContext.setRemark(e.getMessage());
        }
    }



    @Override
    public CommonResult<NotifyOrderTransferDto> orderTransferStatusParse(HttpServletRequest request, ProviderChannelConfigDO providerChannelConfigDO) {
        return null;
    }

    @Override
    public void queryChannelTransfer(ChannelTransferContext channelTransferContext) {
        log.info("合利宝单笔转账查询 payOrderCode:{}", channelTransferContext.getOrderTransfer().getPayOrderNo());
        CommonResult<HeliPayEatrxConfig> configCommonResult = heliPayEatrxConfig(channelTransferContext.getProviderChannelConfig(), channelTransferContext.isTest());
        if (!configCommonResult.isSuccess()) {
            channelTransferContext.setRemark(configCommonResult.getMsg());
            channelTransferContext.setProcessStatus(false);
            return;
        }
        HeliPayEatrxConfig heliPayEatrxConfig = configCommonResult.getData();
        Map<String, Object> params = new HashMap<>();
        OrderTransferDO orderTransfer = channelTransferContext.getOrderTransfer();
        HeliPayEatrxAppChannelParams outMerchantReportDto = heePayAppChannelParams(channelTransferContext.getMerchantAppChannelDO());
        params.put("outUserId", outMerchantReportDto.getUserId());
        params.put("orderNum", orderTransfer.getPayOrderNo());
        String url = url(channelTransferContext.isTest()) + "/ea/transferQuery";
        try {
            // 再提交数据
            CommonResult<HeePayEatrxTransferQueryRes> commonResult = transferRequest(params, url, HeePayEatrxTransferQueryRes.class, heliPayEatrxConfig);
            if (!commonResult.isSuccess()) {
                channelTransferContext.setProcessStatus(false);
                channelTransferContext.setRemark(commonResult.getMsg());
                return;
            }
            HeePayEatrxTransferQueryRes eatrxTransferQueryRes = commonResult.getData();
            if (!eatrxTransferQueryRes.success()) {
                channelTransferContext.setProcessStatus(false);
                channelTransferContext.setRemark(eatrxTransferQueryRes.getRetMsg());
                return;
            }
            OrderTransferDO updateOrderTransfer = new OrderTransferDO();
            channelTransferContext.setUpdateOrderTransfer(updateOrderTransfer);
            updateOrderTransfer.setChannelOrderNo(eatrxTransferQueryRes.getSerialNumber());
            switch (eatrxTransferQueryRes.getStatus()) {
                case "FAIL":
                    updateOrderTransfer.setStatus(MerchantEnum.PROCESS_STATUS.FAIL.getCode());
                    break;
                case "SUCCESS":
                    updateOrderTransfer.setStatus(MerchantEnum.PROCESS_STATUS.SUCCESS.getCode());
                    break;
                default:
                    updateOrderTransfer.setStatus(MerchantEnum.PROCESS_STATUS.DOING.getCode());
            }
            if (StringUtils.hasText(eatrxTransferQueryRes.getCompleteDate())) {
                try {
                    updateOrderTransfer.setSuccessTime(DateUtils.shanghaiDate(eatrxTransferQueryRes.getCompleteDate(), "yyyy-MM-dd HH:mm:ss"));
                }
                catch (Exception e) {
                    log.error("合利宝转账订单查询返回 时间格式化错误 dateTime:{},message:{}", eatrxTransferQueryRes.getCompleteDate(), e.getMessage());
                }
            }
            updateOrderTransfer.setMessage(eatrxTransferQueryRes.getDescription());
        }
        catch (Exception e) {
            channelTransferContext.setProcessStatus(false);
            channelTransferContext.setRemark(e.getMessage());
        }
    }

    @Override
    public String callBackResponse(CommonResult commonResult) {
        if (commonResult.isSuccess()) {
            return "success";
        }
        return commonResult.getMsg();
    }
}
